package com.chezhujie.www.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.chezhujie.www.service.*;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.chezhujie.www.core.quartz.AppMap;
import com.chezhujie.www.domain.Czjdeliveryadd;
import com.chezhujie.www.domain.Czjuserinfo;
import com.chezhujie.www.domain.Czjusermess;
import com.chezhujie.www.domain.vo.CzjuserAll;
import com.chezhujie.www.domain.vo.CzjuserAndMember;
import com.chezhujie.www.utils.ImgBase64Util;
import com.chezhujie.www.utils.SendMessageUtil;
import com.chezhujie.www.utils.UUIDUtils;

@Controller
public class CzjuserinfoController extends BaseController {

	private static final Logger log = LoggerFactory
			.getLogger(CzjuserinfoController.class);

	// 登陆
	@RequestMapping("login.do")
	public void login(@RequestParam(required = true) String telephone,
			@RequestParam(required = true) String password,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {

			Czjuserinfo czjuserinfo = czjuserinfoService
					.loginUserInfo(telephone.trim());
			if (null != czjuserinfo && !"".equals(czjuserinfo)) {
				Map<String, Object> result = new HashMap<String, Object>();
				String pwd = czjuserinfo.getPassword();
				if (StringUtils.isNotBlank(pwd)) {

					if (pwd.equals(password.trim())) {
						
					if(czjuserinfo.getEnable().equals("N")){
						jsonResult(0, "162", "用户已被锁定", result, response);		
						return ;
						}

						result.put("userId", czjuserinfo.getId());
						result.put("nickname", czjuserinfo.getNickname());
						result.put("phone", czjuserinfo.getTelephone());

						jsonResult(1, "103", "登陆成功", result, response);
						return;
					} else {
						jsonResult(0, "104", "密码错误", result, response);
						return;
					}
				} else {
					jsonResult(0, "105", "用户密码为空", result, response);
					return;
				}

			} else {
				jsonResult(0, "102", "手机号码不存在，尚未注册", "", response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("101", e);
			jsonResult(0, "101", "登陆异常", "", response);

		}

	}

	// 注册
	@RequestMapping("register.do")
	public void register(Czjuserinfo czjuserinfo,
			@RequestParam(required = true) String pid,
			@RequestParam(required = true) String code,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, ModelMap model) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();

		if (StringUtils.isBlank(czjuserinfo.getTelephone())) {
			jsonResult(0, "106", "手机号码不能为空", "", response);
			return;
		}
		if (StringUtils.isBlank(czjuserinfo.getPassword())) {
			jsonResult(0, "105", "用户密码为空", result, response);
			return;
		}
		try {

			// 判断手机号码是否已经注册
			Czjuserinfo cinfo = czjuserinfoService.loginUserInfo(czjuserinfo
					.getTelephone());
			if (null != cinfo) {
				jsonResult(0, "108", "手机号码已经注册", result, response);
				return;
			}
			 pid=czjuserinfo.getTelephone();
			// 校验短信验证的时效 和 对错
			if (AppMap.getVcode(pid) == null) {
				jsonResult(0, "110", "验证码失效", result, response);
				return;
			}
			if (!request.getParameter("code").equals(
					AppMap.getVcode(pid))) {
				jsonResult(0, "110", "验证码不正确", result, response);
				return;
			}
			//删除短信验证码
			AppMap.removeVcode(pid);
			//
			czjuserinfo.setType(0); // 用户类型
			czjuserinfo.setCreatetime(new Date());
			czjuserinfo.setEnable("Y");
			czjuserinfo.setIsdelete("0");
			czjuserinfo.setIdentity("0");
			czjuserinfoService.insertCzjuserinfoByAuto(czjuserinfo);
			int lastInsertId = czjuserinfoService.findlastInsert();
			result.put("userId", lastInsertId);

			jsonResult(1, "108", "注册成功", result, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("注册用户异常", e);
			jsonResult(0, "107", "系统异常", "", response);

		}

	}
	

	@RequestMapping("getRandomStr")
	public void getRandom(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		// 随机数保存在服务器 有效期5分钟
		// 随机数一旦使用就消除
		
		try {
			String str=UUIDUtils.getUUID();
			AppMap.setRandomStr(str, UUIDUtils.getDateUUID());//随机数
			jsonResult(1, "", "", str, response);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "173", "生成随机数失败", "", response);
		}
		
	}

	/**
	 *
	 * 方法名：sendMSM 创建人：RUI 时间：2017年5月2日-上午9:31:58
	 * 
	 * @param pid
	 * @param telephone
	 * @param type
	 *            1注册验证码 2审核通过验证码 3审核不通过验证码 4忘记密码验证码
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("sendMSM.do")
	public void sendMSM(@RequestParam(required = true) String pid,
			@RequestParam(required = true) String telephone,
			@RequestParam(required = true) String type,@RequestParam(required = true) String str,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			
			String random=AppMap.getRandomStr(str);
			if(null==random){
				jsonResult(0, "174", "短信发送异常，非法请求", "", response);
				return ;
			}
			AppMap.removeRandomStr(str);
			
			Map<String, Object> map=new HashMap<String, Object>();
				map.put("telephone", telephone);
			int i=czjuserinfoService.findPhone(map);
			if(type.equals("1")){
				if(i>0){
					jsonResult(0, "141", "该手机号码已经注册,短信发送失败", "", response);
					return ;
				}	
			}
			if(type.equals("4")){
				if(i<=0){
					jsonResult(0, "142", "系统没有该手机号码，短信发送失败", "", response);
					return ;
				}
			}
			
			
			HashMap<String, Object> result = SendMessageUtil.send(telephone,
					response, request, type);
			if ("000000".equals(result.get("statusCode"))) {
				String ranStr = (String) result.get("ranStr");// 验证码
				AppMap.setVcode(ranStr, telephone);
				result.remove("ranStr");
				result.put("pp", telephone);
				
				

				jsonResult(1, "109", "短信发送成功", result, response);
			} else {
				/*
				 * 异常返回输出错误码和错误信息 System.out.println("错误码=" +
				 * result.get("c") + " 错误信息= " +
				 * result.get("statusMsg"));
				 */
				result.remove("ranStr");
				String statusCode=(String) result.get("statusCode");
				if(statusCode.equals("160040")){
					jsonResult(0, "176", "验证码超出今日所发上限", result, response);
					return ;
				}
				jsonResult(0, "145", "短信方系统错误", result, response);

			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("获取验证码出错", e);
			jsonResult(0, "110", "短信发送失败", "", response);
		}

	}

	/**
	 * 忘记密码 方法名：forgotPwd 创建人：RUI 时间：2017年5月2日08:55:57
	 * 
	 * @param czjusermess
	 * @param file
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("forgotPwd.do")
	public void forgotPwd(@RequestParam(required = true) String phone,
			@RequestParam(required = true) String password,
			@RequestParam(required = true) String code,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session, ModelMap model) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();

		try {

			// 校验短信验证的时效 和 对错
			if (AppMap.getVcode(phone) == null) {
				jsonResult(0, "110", "验证码失效", result, response);
				return;
			}
			if (!request.getParameter("code").equals(
					AppMap.getVcode(phone))) {
				jsonResult(0, "110", "验证码不正确", result, response);
				return;
			}
			AppMap.removeVcode(phone);
			// 修改密码
			Czjuserinfo czjuserinfo = new Czjuserinfo();
			czjuserinfo.setPassword(password);
			czjuserinfo.setTelephone(phone);
			czjuserinfoService.updatePwdByPhone(czjuserinfo);
			jsonResult(1, "121", "修改密码成功", result, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("修改密码异常", e);
			jsonResult(0, "107", "系统异常", "", response);
		}

	}

	/**
	 * 
	 * 方法名：findUserById 根据用户id查询会员状态 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("findUserById")
	public void findUserById(@RequestParam(required = true) Integer id,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			CzjuserAndMember andMember = czjuserinfoService
					.getCzjuserAndMember(map);
			if (null == andMember) {
				jsonResult(0, "126", "用户不存在", "", response);
				return;
			}

			jsonResult(1, "", "", andMember, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("125", e);
			jsonResult(0, "125", "查询用户会员信息失败", "", response);
		}

	}

	/**
	 * 
	 * 方法名：findUserAll 查询用户基本信息和收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("findUserAll")
	public void findUserAll(@RequestParam(required = true) Integer id,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			CzjuserAll czjuserAll = czjuserinfoService.findUserAll(map);
			jsonResult(1, "", "", czjuserAll, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("127", e);
			jsonResult(0, "127", "查询用户基本信息失败", "", response);
		}

	}

	/**
	 * 
	 * 方法名：updateUser 修改用户基本信息 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("updateUser")
	public void updateUserById(@RequestParam(required = true) Integer id,
			HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = false) String picPath, ModelMap model)
			throws Exception {

		try {
			String nickname = request.getParameter("nickname");
			String usermessId = request.getParameter("usermessId");
			String sex = request.getParameter("sex");
			String reginon = request.getParameter("reginon");
			String deliveryaddId = request.getParameter("deliveryaddId");
			String address = request.getParameter("address");

			//个人表 begin
			Czjuserinfo czjuserinfo = new Czjuserinfo();
			czjuserinfo.setId(id);
			czjuserinfo.setNickname(nickname);
			czjuserinfoService.updateCzjuserinfo(czjuserinfo);
			//end
			
			//收货地址 begin
			Czjdeliveryadd czjdeliveryadd = new Czjdeliveryadd();
			czjdeliveryadd.setDeliveryaddId(deliveryaddId);
			czjdeliveryadd.setAddress(address);
			if (StringUtils.isNotBlank(deliveryaddId)) {

				czjdeliveryaddService.updateDelivery(czjdeliveryadd);
			}
			
			//end
			
			//用户关联基本信息
			Czjusermess czjusermess = czjusermessService.queryByUserinfoId(id);
			if(null==czjusermess){
				czjusermess=new Czjusermess();
				if(null !=sex){
					czjusermess.setSex(Integer.valueOf(sex));
				}
				czjusermess.setUserinfoId(id);
				czjusermess.setReginon(reginon);
				czjusermess.setNoComment("N");//默认可评论
				if (picPath!=null && picPath.length() > 0) {

					String pathRoot = request.getSession().getServletContext()
							.getRealPath("");
					String picName = UUIDUtils.getDateUUID();
					String path = "/upload/" + picName+"-"+System.currentTimeMillis() + ".jpg";// 数据库保存路径
					boolean isTrue = ImgBase64Util.generateImage(picPath, pathRoot
							+ path);
					if (isTrue == false) {
						jsonResult(0, "120", "转存头像失败", "", response);
						return;
					}

					czjusermess.setPicPath(path);
//					String mediumPic = genernateMediumPic("/upload/comments/pic/",basePath,listPicfile.get(i).getPicPath(),listPicfile.get(i).getCommentsId());
					String mediumPic = apitwjService.genernateMediumPic("/upload/comments/pic/",request,path,czjusermess.getUsermessId());
					czjusermess.setPicPath(mediumPic);
				}
				czjusermessService.insertUsermess(czjusermess);
			}else{
				if(null !=sex){
					czjusermess.setSex(Integer.valueOf(sex));
				}
				if(null==czjusermess.getNoComment()){
					czjusermess.setNoComment("N");//默认可评论
				}
				czjusermess.setUserinfoId(id);
				czjusermess.setReginon(reginon);
				if (picPath!=null && picPath.length() > 0) {

					String pathRoot = request.getSession().getServletContext()
							.getRealPath("");
					String picName = UUIDUtils.getDateUUID();
					String path = "/upload/" + picName+"-"+System.currentTimeMillis() + ".jpg";// 数据库保存路径
					boolean isTrue = ImgBase64Util.generateImage(picPath, pathRoot
							+ path);
					if (isTrue == false) {
						jsonResult(0, "120", "转存头像失败", "", response);
						return;
					}

					czjusermess.setPicPath(path);
//					String mediumPic = genernateMediumPic("/upload/comments/pic/",basePath,listPicfile.get(i).getPicPath(),listPicfile.get(i).getCommentsId());
					String mediumPic = apitwjService.genernateMediumPic("/upload/comments/pic/",request,path,czjusermess.getUsermessId());
					czjusermess.setPicPath(mediumPic);

				}
				
				czjusermessService.updateUsermess(czjusermess);
			}
			
		
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", id);
			jsonResult(1, "", "", map, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("128", e);
			jsonResult(0, "128", "修改用户信息失败", "", response);
		}

	}

	/**
	 * 
	 * 方法名：findDeliveryById 查询用户收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("findDeliveryById")
	public void findDeliveryById(@RequestParam(required = true) Integer id,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userinfoId", id);
			map.put("del", 1);
			List<Czjdeliveryadd> czjdeliveryadds = czjdeliveryaddService
					.findDeliById(map); // 根据用户id查询收货地址
			jsonResult(1, "", "", czjdeliveryadds, response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("129", e);
			jsonResult(0, "129", "查询用户收货地址错误", "", response);
		}
	}

	/**
	 * 
	 * 方法名：insertDelivery 新增用户收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("insertDelivery")
	public void insertDelivery(@RequestParam(required = true) Integer id,
			Czjdeliveryadd czjdeliveryadd, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws Exception {

		try {
			czjdeliveryadd.setUserinfoId(id);
			czjdeliveryadd.setCreatetime(new Date());
			czjdeliveryadd.setDel(1);
			
			if(null==czjdeliveryadd.getDef())
				czjdeliveryadd.setDef(0);
			czjdeliveryaddService.insertDelivery(czjdeliveryadd);
			jsonResult(1, "", "", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("130", e);
			jsonResult(0, "130", "新增用户收货地址错误", "", response);
		}

	}

	/**
	 * 
	 * 方法名：updateDeliveryDef 设置用户默认收货地址 创建人：RUI 时间：2017年5月31日-下午7:52:56
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 *             void
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("updateDeliveryDef")
	public void updateDeliveryDef(@RequestParam(required = true) Integer id,
			@RequestParam(required = true) String deliveryaddId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			// 默认地址只能有一个，首先把这个用户的其它收货地址设置为0
			Czjdeliveryadd czjdeliveryadd = new Czjdeliveryadd();
			czjdeliveryadd.setUserinfoId(id);
			czjdeliveryadd.setDef(0);
			czjdeliveryaddService.updateDeliveryDef(czjdeliveryadd);
			czjdeliveryadd.setDeliveryaddId(deliveryaddId);
			czjdeliveryadd.setDef(1);
			czjdeliveryaddService.updateDelivery(czjdeliveryadd);
			jsonResult(1, "", "", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("131", e);
			jsonResult(0, "131", "设置用户默认收货地址错误", "", response);
		}
	}

	@RequestMapping("payUpdateHy")
	public void payUpdateHy(@RequestParam(required = true) Integer userinfoId,
			@RequestParam(required = true) String idCard,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			Czjusermess czjusermess=czjusermessService.queryByUserinfoId(userinfoId);
			if(null==czjusermess){
				Czjusermess mess=new Czjusermess();
				mess.setIdCard(idCard);
				mess.setUsermessId(UUIDUtils.getUUID());
				mess.setUserinfoId(userinfoId);
				czjusermessService.insertUsermess(mess);
				jsonResult(1, "", "", "", response);
				return ;
			}
			czjusermess.setIdCard(idCard);
			czjusermessService.updateUsermess(czjusermess);
			jsonResult(1, "", "", "", response);
		} catch (Exception e) {
			jsonResult(1, "", "", "", response);
		}
	}
	
	public boolean volidateVodeType(String type) {
		if (type.equalsIgnoreCase("mp4") || type.equalsIgnoreCase("avi")
				|| type.equalsIgnoreCase("rmvb")
				|| type.equalsIgnoreCase("quicktime"))
			return true;
		else
			return false;
	}
	
	@RequestMapping("getNoComment")
	public void getNoComment(@RequestParam(required = true) Integer userinfoId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {

		try {
			String noComment=czjusermessService.getNoComment(userinfoId);
			if(null==noComment){
			noComment="N";	
			}
			jsonResult(1, "", "",noComment, response);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(1, "", "", "", response);
		}
	}

	@Resource
	private CzjuserinfoService czjuserinfoService;

	@Resource
	private CzjmemberService czjmemberService;

	@Resource
	private CzjdeliveryaddService czjdeliveryaddService;

	@Resource
	private CzjusermessService czjusermessService;
	@Resource
	private ApitwjService apitwjService;

}